﻿using DotNetty.Wraper;
using Examples.Common;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;

namespace WebSocket.Server
{
    class Program
    {
        static async Task Main(string[] args)
        {
            ILogger _logger = new CNative.Logging.ConfigLogger();// LoggingHelper.Logger;

            var option = new ServerOption();
            option.Port = Examples.Common.ServerSettings.Port;
            option.Path= Examples.Common.ServerSettings.Path;
            option.UseLibuv = ServerSettings.UseLibuv;
            if (ServerSettings.IsSsl)
            {
                option.Certificate = Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx");
                option.CertificatePassword = "password";
            }
            var theServer = await SocketBuilderFactory.GetWebSocketServerBuilder(option)
                .OnConnectionClose((server, connection) =>
                {
                    _logger.LogInformation($"连接关闭,连接名[{connection.ConnectionName}],当前连接数:{server.GetConnectionCount()}");
                })
                .OnException(ex =>
                {
                    _logger.LogError($"服务端异常:{ex.Message}");
                })
                .OnNewConnection((server, connection) =>
                {
                    connection.ConnectionName = $"名字{connection.ConnectionId}";
                    _logger.LogDebug($"新的连接:{connection.ConnectionName},当前连接数:{server.GetConnectionCount()}");
                })
                .OnRecieve((server, connection, msg) =>
                {
                    _logger.LogInformation($"服务端:数据{msg}");
                    //connection.Send(msg);
                    server.Send(msg.GetBytes(),"");
                })
                .OnSend((server, connection, msg) =>
                {
                    _logger.LogInformation($"向连接名[{connection.ConnectionName}]发送数据:{msg}");
                })
                .OnChannelUnregistered((server, connection, channel) =>
                {
                    _logger.LogDebug("ChannelUnregistered: " + channel.Id);
                })
                .OnChannelRegistered((server, channel) =>
                {
                    //channel.WriteAndFlushAsync("ChannelUnregistered");
                    _logger.LogDebug("ChannelRegistered: " + channel.Id);
                })
                .OnServerStarted(server =>
                {
                    _logger.LogInformation($"服务启动");
                }).BuildAsync((pipeline) =>
                    {
                    });

            Console.ReadLine();
        }
    }
}
